<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Models\GoodsCart;
use App\Models\GoodsOrder;
use App\Models\GoodsOrderDetails;
use App\Models\GoodsSku;
use App\Models\Supplier;
use App\Services\GoodsCartService;
use App\Services\GoodsOrderService;
use App\Services\GoodsService;
use App\Services\GoodsSpecsService;
use App\Services\SupplierService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Snowflake;

class GoodsOrderController extends AdminController
{
    //添加
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            // 'users_id' => 'required|integer|digits_between:1,20|min:1',
            'phone' => 'required|string',
            'contact_person' => 'required|string', //联系人
            'is_cart' => 'required|integer', //是否是购物车 0是购物车 1不是
            'school_id' => 'integer',
            'address' => 'required|string',
            'sku_id' => 'required',
            'message' => 'string'
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $validator = Validator::make($request->all(), [
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_PHONE_UNREGISTERED);
        }
        $phone = $request->phone;
        $school_id = $request->school_id;
        if(!isset($school_id)){
            return $this->fail(CodeResponse::AUTH_SCHOOL_NOT_SET_ID);
        }
         $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能查看订单信息']);
        }
        $sms = new SmsController(); //短信服务
        $order_num = Snowflake::nextId(); //订单号
        $skuIdArr = $request->sku_id;
        $skuIdArr = is_array($skuIdArr) ? $skuIdArr : json_decode($skuIdArr,true);
        if(isset($request->is_cart) && $request->is_cart == 0){ //购物车订单
            $goodsCart = GoodsCartService::getInstance()->list($users_id,$skuIdArr);

            if(count($goodsCart) < 1){
                return $this->fail(CodeResponse::GOODS_ORDER_SKU);
            }
            if(!$goodsCart[0]){
                return $this->fail($goodsCart);
            }
            $goodsCart = $goodsCart->toArray();
            $price = array_sum(array_column($goodsCart,'total_price'));

            $orderModel = new GoodsOrder();
            $orderModel->users_id = $users_id;
            $orderModel->order_num = $order_num;
            $orderModel->phone= $phone;
            $orderModel->school_id = $school_id;
            $orderModel->total_price = $price;
            $orderModel->address= $request->address;
            $orderModel->message= $request->message;
            $orderModel->contact_person = $request->contact_person; //20230821新增
            $orderModel->order_type= 1;
            $orderModel->status= 0;
            $orderModel->save();

            //删除购物车里的数据并减少库存
            foreach ($goodsCart as $v){
                $orderOrderDetailsModel = new GoodsOrderDetails();
                $orderOrderDetailsModel->order_num = $order_num;
                $orderOrderDetailsModel->goods_id= $v['goods_id'];
                $orderOrderDetailsModel->sku_id= $v['sku_id'];
                $orderOrderDetailsModel->num= $v['num'];
                $orderOrderDetailsModel->price= $v['total_price'];
                $orderOrderDetailsModel->title= $v['title'].'-'.$v['sku'];
                $orderOrderDetailsModel->sku= $v['sku'];
                $orderOrderDetailsModel->image= $v['image'];
                $orderOrderDetailsModel->save();
                //减少库存数量
                GoodsService::getInstance()->reduceSkuNum($v['sku_id'],$v['num']);
                //删除购物车
                $goodsCart = GoodsCart::find($v['id']);
                $goodsCart->delete();
            }
            $sms->Send($phone,1819875,['您好']);
        }else{
            //直接下单
            $sku_id = $skuIdArr[0];
            $goodsSku = GoodsService::getInstance()->getSkuInfo($sku_id);
            if(!$goodsSku){
                return $this->fail(CodeResponse::GOODS_ORDER_SKU);
            }
            if(!$request->num){
                return $this->fail(CodeResponse::GOODS_ORDER_NUM);
            }
            $sku = GoodsSku::where('id',$sku_id)->first();

            if(($request->num && $sku->stock < $request->num) ||($sku->stock < 1)){
                return $this->fail(CodeResponse::GOODS_CART_STOCK);
            }
            $goodsSku = $goodsSku->toArray();
            $goodsSpecsValueId = explode(',',$goodsSku['goods_specs_value_id']);
            $specsValuesArr = GoodsSpecsService::getInstance()->dealSpecsVal($goodsSpecsValueId);
            $specsValues = implode(' ',$specsValuesArr);

            $orderModel = new GoodsOrder();
            $orderModel->users_id = $users_id;
            $orderModel->order_num = $order_num;
            $orderModel->order_type = 1;
            $orderModel->phone= $request->phone;
            if($request->num){
                $orderModel->total_price = ($goodsSku['price']*$request->num);
            }else{
                $orderModel->total_price = $goodsSku['price'];
            }
            $orderModel->address= $request->address;
            $orderModel->message= $request->message;
            $orderModel->contact_person = $request->contact_person; //20230821新增
            $orderModel->status= 0;
            $orderModel->save();

            $orderOrderDetailsModel = new GoodsOrderDetails();
            $orderOrderDetailsModel->order_num = $order_num;
            $orderOrderDetailsModel->goods_id= $goodsSku['goods_id'];
            $orderOrderDetailsModel->sku_id= $sku_id;
            $orderOrderDetailsModel->num= $request->num;
            $orderOrderDetailsModel->price= $goodsSku['price'];
            $orderOrderDetailsModel->title= $goodsSku['title'].'-'.$specsValues;
            $orderOrderDetailsModel->sku= $specsValues;
            $orderOrderDetailsModel->image= $goodsSku['image'];
            $orderOrderDetailsModel->save();
            //减少库存数量
            GoodsService::getInstance()->reduceSkuNum($sku_id,$request->num);

            $sms->Send($phone,1819875,['您好']);
        }
        //查看该学校是否分配给供应商如果分配了将产生的订单分配给学校
        if(isset($school_id)){
            $supplier = SupplierService::getInstance()->allocationSchoolSupplier($school_id);
            if(isset($supplier->supplier_id)) {
                SupplierService::getInstance()->allocationOrder($supplier->supplier_id,$order_num);
            }
        }

        return $this->success($orderModel->id);
    }

    //游客添加
    public function touristAdd(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string',
            'address' => 'required|string',
            'contact_person' => 'required|string', //联系人
            'sku_id' => 'required|string',
            'num' => 'required|integer',
            'message' => 'string'
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $validator = Validator::make($request->all(), [
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_PHONE_UNREGISTERED);
        }
        $phone = $request->phone;
        $sms = new SmsController(); //短信服务
        $sku_id = $request->sku_id;
        $order_num = Snowflake::nextId(); //订单号

        $goodsSku = GoodsService::getInstance()->getSkuInfo($sku_id);
        if(!$goodsSku){
            return $this->fail(CodeResponse::GOODS_ORDER_SKU);
        }
        $sku = GoodsSku::where('id',$sku_id)->first();

        if(($request->num && $sku->stock < $request->num) ||($sku->stock < 1)){
            return $this->fail(CodeResponse::GOODS_CART_STOCK);
        }
        $goodsSku = $goodsSku->toArray();
        $goodsSpecsValueId = explode(',',$goodsSku['goods_specs_value_id']);

        $specsValuesArr = GoodsSpecsService::getInstance()->dealSpecsVal($goodsSpecsValueId);
        $specsValues = implode(' ',$specsValuesArr);
        $orderModel = new GoodsOrder();
        $orderModel->order_num = $order_num;
        $orderModel->order_type = 0;
        $orderModel->phone=  $phone;
        if($request->num){
            $orderModel->total_price = ($goodsSku['price']*$request->num);
        }else{
            $orderModel->total_price = $goodsSku['price'];
        }

        $orderModel->address= $request->address;
        $orderModel->message= $request->message;
        $orderModel->contact_person = $request->contact_person; //20230821新增
        $orderModel->status= 0;
//        dd($request->contact_person);
        $orderModel->save();

        $orderOrderDetailsModel = new GoodsOrderDetails();
        $orderOrderDetailsModel->order_num = $order_num;
        $orderOrderDetailsModel->goods_id= $goodsSku['goods_id'];
        $orderOrderDetailsModel->sku_id= $sku_id;
        $orderOrderDetailsModel->num= $request->num;
        $orderOrderDetailsModel->price= $goodsSku['price'];
        $orderOrderDetailsModel->title= $goodsSku['title'].'-'.$specsValues;
        $orderOrderDetailsModel->sku= $specsValues;
        $orderOrderDetailsModel->image= $goodsSku['image'];
        $orderOrderDetailsModel->save();
        //减少库存数量
        GoodsService::getInstance()->reduceSkuNum($sku_id,$request->num);
        $sms->Send($phone,1819875,['您好']);
        return $this->success($orderModel->id);
    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|digits_between:1,20|min:1',
            'phone' => 'required|string',
            'address' => 'required|string',
            'contact_person' => 'required|string',
            'status' => 'required|integer',
            'message' => 'string'
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $order = GoodsOrder::find($request->id);
        $order->status = $request->status;
        $order->phone= $request->phone;
        $order->address= $request->address;
        $order->contact_person = $request->contact_person; //20230821新增
        $order->message= $request->message;
        if(isset($request->status)){
            $order->status= $request->status;
        }
        if(isset($request->phone)){
            $order->phone= $request->phone;
        }
        if(isset($request->address)){
            $order->address= $request->address;
        }
        if(isset($request->message)){
            $order->message= $request->message;
        }
        $order->save();
        return $this->success($order->id);
    }
    //订单列表
    public function  list(Request $request){
        $validator = Validator::make($request->all(), [
            'order_num' => 'string',
            'page' => 'integer',
            'limit' => 'integer',
            'sort' => 'string',
            'order' => 'string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $order_num = $request->input('order_num');
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $sort = $request->input('sort','created_at');
        $order = $request->input('order','asc');
        $list = GoodsOrderService::getInstance()->list($page,$limit,$sort,$order,$order_num);
        return $this->success($list);
    }
    //订单信息
    public function  info(Request $request){
        $validator = Validator::make($request->all(), [
            'order_num' => 'string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $order_num = $request->input('order_num');
        $info = GoodsOrderService::getInstance()->info($order_num);
        return $this->success($info);
    }
    //个人中心订单信息
    public function  userInfo(Request $request){
        $validator = Validator::make($request->all(), [
            'order_num' => 'string',
            'title' => 'string',
        ]);
        $users_id = $request->input('users_id');
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能查看订单信息']);
        }
        $order_num = $request->input('order_num');
        $title = $request->input('title');
        $info = GoodsOrderService::getInstance()->userInfo($users_id,$order_num,$title);
        return $this->success($info);
    }

    //更新订单状态
    public function stateUpdate(Request $request){
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|digits_between:1,20|min:1',
            'status' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        if (!in_array($request->status,[0,1,2,3,4,5,6])) {
            return $this->fail(CodeResponse::PARAM_STATUS);
        }
        $goodsOrder = GoodsOrder::find($request->id);
        if(!$goodsOrder){
            return $this->fail(CodeResponse::GOODS_ORDER_NO);
        }
        $goodsOrder->status = $request->status;
        $goodsOrder->save();
        return $this->success($goodsOrder->id);
    }
    //库存数量
    public function inventoryNum(Request $request){
        $validator = Validator::make($request->all(), [
            'sku_id' => 'required|string',
            'num' => 'integer',

        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $sku_id = $request->sku_id;
        $goodsSku = GoodsService::getInstance()->getSkuInfo($sku_id);
        if(!$goodsSku){
            return $this->fail(CodeResponse::GOODS_ORDER_SKU);
        }
        $sku = GoodsSku::where('id',$sku_id)->first();
        if(($request->num && $sku->stock < $request->num) ||($sku->stock < 1)){
            return $this->fail(CodeResponse::GOODS_CART_STOCK);
        }
        return $this->success();
    }

}
